package client;

import java.io.*;
import java.net.*;
import java.util.*;

import msgs.*;
/**
 * Constantly listens for incoming PM Messages
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 * @author Ryan Kortmann
 */
public class PMListener extends Thread
{
	/**
	 * This is the queue of incoming messages
	 */
	protected static Vector<SimpleMsg> inQ;
	
	private static boolean go;
	private static int port;
	
	private ServerSocket ssock;
	private Socket sock;
	private ObjectInputStream ois;
	
	private SimpleMsg msg;
	
    public PMListener(int port)
    {
    	this.port = port;
    	inQ = new Vector<SimpleMsg>();
		go = true;
		
		try
		{
			ssock = new ServerSocket(port);
		}
		catch (IOException e)
		{
			go = false;
			System.err.println("Unable to open port " + port + " for listening!");
		}
    }
    
    public void run()
    {
		while(go)
		{
			try
			{
				// process inQ, block until we get a conndection
				sock = ssock.accept();
				
				ois = new ObjectInputStream(sock.getInputStream());

				msg = (SimpleMsg) ois.readObject();
				inQ.add(msg);
				ois.close();
				//sock.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		try {
			ois.close();
			sock.close();
			ssock.close();
		}
		catch(Exception e) {}
	}
    
    /**
     * This kills of the PMListener thread, clean shutdown
     */
    public static void killPMListener() {
		while (go) {
			if (inQ.isEmpty()) go = false;
			else try {
				Thread.sleep(10);
			} 
			catch (Exception e) {}
		}
	}
		
}